package com.liugh.asyn;

/**
 * Created by xingzhong on 2018/7/19.
 * 异步执行的任务
 */
public abstract class AsyncJob<R> implements Comparable<AsyncJob>, Runnable {

    /**
     * 默认队列
     */
    public static final String DEFAULT_QUEUE = "default";


    private int priority = 0;
    /**
     * 异步执行队列标志
     */
    private String queue = DEFAULT_QUEUE;

    /**
     * 异步执行任务回调
     */
    protected AsyncJobListener mAsyncJobListener;


    public AsyncJob() {}

    public AsyncJob(int priority) {
        this.priority = priority;
    }

    public AsyncJob(String queue) {
        this.queue = queue;
    }
    public AsyncJob(int priority, String queue) {
        this.priority = priority;
        this.queue = queue;
    }

    @Override
    public void run() {
        AsyncJobResult<R> result = null;
        if (null == mAsyncJobListener || mAsyncJobListener.beforeExecute(this)) {
            result = runJob();
        }
        if (null != mAsyncJobListener) {
            mAsyncJobListener.afterExecute(this, result);
        }
    }

    /**
     * 执行具体的job任务
     * @return
     */
    protected abstract AsyncJobResult<R> runJob();

    public AsyncJobListener getAsyncJobListener() {
        return mAsyncJobListener;
    }

    public void setAsyncJobListener(AsyncJobListener asyncJobListener) {
        mAsyncJobListener = asyncJobListener;
    }

    public String getQueue() {
        return queue;
    }

    public void setQueue(String queue) {
        this.queue = queue;
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public int compareTo(AsyncJob o) {
        return this.getPriority() - o.getPriority();
    }


}
